/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ImprimirPlanillaLlamado.java
 *
 * Created on 21-ene-2013, 15:08:52
 */
package gui.reportes;

import controladores.ControladorPrincipal;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import utilidades.JFrameConFondo;

/**
 *
 * @author NiCo
 */
public class OtrosDatos extends JFrameConFondo implements Printable {

    private Image icono = new ImageIcon(getClass().getResource("/imagenes/logo.png")).getImage();
    private String path;
    private final List<Object[]> datos;
    private final int anio;

    /** Creates new form ImprimirPlanillaLlamado */
    public OtrosDatos(List<Object[]> datos, int anio, String titulo) {
        try {
            initComponents();
            XYDataset dataset = null;
            JFreeChart chart = null;
            if (titulo.equals("Casos por mes")) {
                dataset = crearDatos(datos);
                chart = crearGrafica(dataset);
            } else {
                dataset = crearOtrosDatos(datos);
                chart = crearGrafica(dataset);
            }
            File archivo = new File(System.getProperty("java.io.tmpdir") + "grafica" + (ControladorPrincipal.getInstance().getGraficas() - 1) + ".png");
            archivo.delete();
            path = System.getProperty("java.io.tmpdir") + "grafica" + ControladorPrincipal.getInstance().getGraficas() + ".png";
            ChartUtilities.saveChartAsPNG(new File(path), chart, 484, 350);
            jPanelConFondo1.setImagen("");
            jPanelConFondo1.setImagen(new ImageIcon(path).getImage());
            ControladorPrincipal.getInstance().setGraficas(ControladorPrincipal.getInstance().getGraficas() + 1);
        } catch (Exception ex) {
        }
        this.datos = datos;
        this.anio = anio;

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCerrar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanelConFondo1 = new utilidades.JPanelConFondo();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerrar-normal.png"))); // NOI18N
        btnCerrar.setBorder(null);
        btnCerrar.setBorderPainted(false);
        btnCerrar.setFocusPainted(false);
        btnCerrar.setName("btnCerrar"); // NOI18N
        btnCerrar.setOpaque(false);
        btnCerrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnCerrarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                btnCerrarMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnCerrarMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnCerrarMouseReleased(evt);
            }
        });
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/titulo-estadistica-casos.png"))); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imprimir.png"))); // NOI18N
        jButton1.setBorderPainted(false);
        jButton1.setFocusPainted(false);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanelConFondo1.setName("jPanelConFondo1"); // NOI18N

        javax.swing.GroupLayout jPanelConFondo1Layout = new javax.swing.GroupLayout(jPanelConFondo1);
        jPanelConFondo1.setLayout(jPanelConFondo1Layout);
        jPanelConFondo1Layout.setHorizontalGroup(
            jPanelConFondo1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 484, Short.MAX_VALUE)
        );
        jPanelConFondo1Layout.setVerticalGroup(
            jPanelConFondo1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 350, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(141, 141, 141)
                        .addComponent(btnCerrar))
                    .addComponent(jPanelConFondo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(182, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(180, 180, 180))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCerrar)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))
                .addGap(11, 11, 11)
                .addComponent(jPanelConFondo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCerrarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMouseEntered

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-activo.png")));     }//GEN-LAST:event_btnCerrarMouseEntered

    private void btnCerrarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMouseExited

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-normal.png")));     }//GEN-LAST:event_btnCerrarMouseExited

    private void btnCerrarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMousePressed

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-click.png")));     }//GEN-LAST:event_btnCerrarMousePressed

    private void btnCerrarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMouseReleased

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-normal.png")));     }//GEN-LAST:event_btnCerrarMouseReleased

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        PrinterJob job = PrinterJob.getPrinterJob();
        Paper hoja = new Paper();
        hoja.setImageableArea(0, 0, 595, 841);
        hoja.setSize(595, 841);
        job.setPrintable(this);
        try {
            // Diálogo para elegir el formato de impresión
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(hoja);
            //pageFormat = job.pageDialog(pageFormat);
            if (job.printDialog()) {
                job.print();
            }
        } catch (Exception e) {
        }

    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private utilidades.JPanelConFondo jPanelConFondo1;
    // End of variables declaration//GEN-END:variables

    @Override
    public int print(Graphics g, PageFormat f, int pageIndex) {
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
        if (pageIndex == 0) {
            try {
                // Imprime "Hola mundo" en la primera pagina, en la posicion 100,100
                Image img = ImageIO.read(new File("src/imagenes/ficha-informe-llamado.png").toURI().toURL());
                g.drawImage(img, 52, 0, 491, 801, null);
            } catch (Exception ex) {
            }
            //datos del caso
            g.setFont(new Font("Tahoma", Font.BOLD, 14));
            g.drawString("Año: " + anio, 59, 152);
            try {
                // Imprime "Hola mundo" en la primera pagina, en la posicion 100,100
                Image img = ImageIO.read(new File(path).toURI().toURL());
                g.drawImage(img, 59, 198, 484, 350, null);
            } catch (Exception ex) {
            }
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }

    private XYDataset crearDatos(List<Object[]> datos) {
        XYSeries serie = new XYSeries("Casos");
        Iterator<Object[]> it = datos.iterator();
        while (it.hasNext()) {
            Object[] obj = it.next();
            serie.add((int) Double.parseDouble(obj[0].toString()), Integer.parseInt(obj[1].toString()));
        }
        XYSeriesCollection result = new XYSeriesCollection();
        result.addSeries(serie);
        return result;
    }

    /**
     * Creates a chart
     */
    private JFreeChart crearGrafica(XYDataset dataset) {

        JFreeChart chart = ChartFactory.createXYLineChart(
                "", // chart title
                "Meses", // x axis label
                "Cant. casos", // y axis label
                dataset, // data
                PlotOrientation.VERTICAL,
                true, // include legend
                true, // tooltips
                false // urls
                );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
        chart.setBackgroundPaint(Color.white);

//        final StandardLegend legend = (StandardLegend) chart.getLegend();
        //      legend.setDisplaySeriesShapes(true);

        // get a reference to the plot for further customisation...
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.lightGray);
        //    plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, true);
        renderer.setSeriesShapesVisible(1, true);
        plot.setRenderer(renderer);

        // change the auto tick unit selection to integer units only...
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
        domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        return chart;

    }

    private XYDataset crearOtrosDatos(List<Object[]> datos) {
        XYSeriesCollection result = new XYSeriesCollection();

        Iterator<Object[]> it = datos.iterator();
        String motivo = datos.get(0)[1].toString();
        XYSeries serie = new XYSeries(motivo);
        result.addSeries(serie);
        while (it.hasNext()) {
            Object[] obj = it.next();
            if (obj[1].toString().equals(motivo)) {
                serie.add((int) Double.parseDouble(obj[0].toString()), Integer.parseInt(obj[2].toString()));
            } else {
                motivo = obj[1].toString();
                serie = new XYSeries(motivo);
                serie.add((int) Double.parseDouble(obj[0].toString()), Integer.parseInt(obj[2].toString()));
                if (!result.getSeries().contains(serie)) {
                    result.addSeries(serie);
                }
            }
        }
        return result;
    }
}
